/**
 * 项目名称:
 *
 * @Author: 夏国倩
 * @Date: 2023/10/12 14:38
 * @Copyright
 */
package multithreading;
/*
以下程序使用线程同步机制保证数据的安全
 */
public class ThreadTest13 {
    public static void main(String[] args) {
        //创建一个公共的账号
        Account2 act=new Account2("actno-001",5000);
        //创建线程对同一个账户取款
        Thread t1=new Thread(new Processor13(act));
        Thread t2=new Thread(new Processor13(act));

        t1.start();
        t2.start();
    }
}
//取款线程
class  Processor13 implements Runnable{
    //账户
    Account2 act;
    //构造器
    Processor13(Account2 act){
    this.act=act;
    }
    @Override
    public void run() {
        act.withdraw(1000);
        System.out.println("取款1000.00成功，余额："+act.getBalance());
    }
}
//创建账户
class Account2{
    private String actno;
    private double balance;

    public Account2() {
    }

    public Account2(String actno, double balance) {
        this.actno = actno;
        this.balance = balance;
    }

    public String getActno() {
        return actno;
    }

    public void setActno(String actno) {
        this.actno = actno;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    @Override
    public String toString() {
        return "Account2{" +
                "actno='" + actno + '\'' +
                ", balance=" + balance +
                '}';
    }
    //对外取款方法
    public void withdraw(double money){ //对当前账户进行取款操作
        //把需要同步的代码，放到同步语句块中
        synchronized (this){
            double after=balance-money;
            //延迟
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //更新余额
            this.setBalance(after);
        }
    }
}
